package com.xmyq.controller;

import com.xmyq.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/file")
public class UploadController {

    @PostMapping("upload")
    public String upload(HttpServletRequest request, HttpServletResponse response, MultipartFile upload) throws IllegalStateException, IOException {
        String realPath = "D:/附件";
        // 判断文件是否为空
        if (!upload.isEmpty()) {
            // 文件保存路径
            // 转存文件
            FileUtils.createDirectory(realPath);
            String name = upload.getOriginalFilename(); //得到上传文件名称
            String filePath = realPath +"/"+  name;  //真实的路径＋名称
            File newFile = FileUtils.getAvailableFile(filePath,0);//获取可以创建的文件名（如果有同名文件存在，参照Windows系统重命名为xxx(2).xxx)
            upload.transferTo(newFile);
            String absolutePath = newFile.getAbsolutePath();
            String suffix = absolutePath.substring(absolutePath.lastIndexOf("."));

           // return "http://202.75.216.132:9999/file/download?source=" + realPath + "/" + newFile.getName();

            return "http://localhost:9999/file/download?source=" + realPath + "/" + newFile.getName();


        }
        return "";
    }

    @RequestMapping("download")
    public void download(@Param("source") String source, HttpServletRequest request, HttpServletResponse response) throws Exception{
        File file = new File(source);
        if (file == null || !file.exists()) {
            throw new FileNotFoundException("请求的文件不存在");
        }
        OutputStream out = null;
        try {
            response.reset();
            response.setContentType("application/octet-stream; charset=utf-8");
            String agent = (String)request.getHeader("USER-AGENT");
            String fileName = file.getName();
            if(agent != null && agent.indexOf("MSIE") == -1) {
// FF
                String enableFileName = "=?UTF-8?B?" + (new String(Base64.getEncoder().encode(fileName.getBytes("UTF-8")))) + "?=";
                response.setHeader("Content-Disposition", "attachment; filename=" + enableFileName); }
            else {
// IE
                String enableFileName = new String(fileName.getBytes("GBK"), "ISO-8859-1");
                response.setHeader("Content-Disposition", "attachment; filename=" + enableFileName);
            }
//			response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
            out = response.getOutputStream();
            out.write(org.apache.commons.io.FileUtils.readFileToByteArray(file));
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}